import 'dart:convert';

import 'package:get/get.dart';
import 'package:get_it/get_it.dart';
import 'package:juming_test/config/app_router_path.dart';
import 'package:juming_test/routes/app_router.dart';
import 'package:juming_test/view_models/domain/domain_filter_view_model.dart';
import 'package:logger/logger.dart';

class DomainListLogic extends GetxController {
  // 页面传参
  String paramsData = '';
  // 域名筛选ViewModel
  final DomainFilterViewModel domainFilterViewModel = Get.put(
    DomainFilterViewModel(),
    tag: 'DomainList',
  );

  @override
  void onReady() {
    super.onReady();
    _initParamsData();
  }

  @override
  void onClose() {
    super.onClose();
    Get.delete<DomainFilterViewModel>(tag: 'DomainList');
  }

  // 初始化页面传参
  void _initParamsData() {
    if (paramsData.isEmpty) {
      return;
    }
    domainFilterViewModel.onReady().then((_) {
      domainFilterViewModel.updateByData(jsonDecode(paramsData));
    });
  }

  // 跳转筛选页面
  Future<void> pushToFilterPage() async {
    final appRouter = GetIt.I<AppRouter>();
    String dataStr = domainFilterViewModel.getParamsDataString();
    final result = await appRouter.pushPath(
      '${AppRouterPath.domainFilter}?data=$dataStr',
    );
    if (result != null && result is String && result.isNotEmpty) {
      try {
        final decodedResult = jsonDecode(Uri.decodeComponent(result));
        domainFilterViewModel.updateByData(decodedResult);
      } catch (e) {
        GetIt.I<Logger>().e('Error: $e');
      }
    }
  }
}
